const app = getApp()
const api = app.globalData.api
Page({
    data: {
        item: [],
        warehouseOption: {},
        from: '',
    },
    confirm: async function () {
        let obj = e.currentTarget.dataset
        if (obj.materialid) {
            wx.navigateTo({
                url: 'materialDetail?id=' + obj.id + '&materialid='+obj.materialid
            })
        }
    },
    formSubmit: async function (e) {
        let data = e.detail.value,
            machiningInData = wx.getStorageSync('machiningInData') ? wx.getStorageSync('machiningInData') : {}
        if (data) {
            if (data.warehouseId.length <= 0) {
                api.showToast('请选择仓库', 'none')
                return
            }
            const id = data.id ? data.id : api.suiji()
            data['id'] = id
            // 初始化部分值
            data['rate'] = api.initNaN(data, 'rate')
            machiningInData[id] = data
            api.showToast('选择成功')
            wx.setStorageSync('machiningInData', machiningInData)
            wx.navigateBack({
                delta: (this.data.from === 'add') ? 1 : 2
            })
        }
    },
    // 时间关系，这个bug 不知道是啥
    onStepperChange(obj) {
        this.setData({['item.num']: obj.detail})
    },
    getWarehouse: async function () {
        let res = await api.curlGet('?cla=inventoryOther&fun=warehouse')
        if (res.code === 1) {
            this.setData({
                warehouseOption: res.data
            })
        }
    },
    funRouting: function (type, detail) {
        const array = detail.value
        switch (type) {
            case 'warehouse':
                this.setData({
                    ['item.warehouseId']: array['value']
                })
                return array['text']
        }
    },
    // 确认选择
    onConfirm: function (e) {
        let obj = e.currentTarget.dataset
        let field = 'item.' + obj.field
        this.setData({
            [obj.target]: false,
            [field]: this.funRouting(obj.field, e.detail),
        })
    },
    showPopup: function (obj) {
        let popup = obj.currentTarget.dataset.show
        if (popup) {
            this.setData({
                [popup]: true
            });
        }
    },
    onLoad: async function (obj) {
        this.getWarehouse()
        const id = obj.id ? obj.id : (obj.materialId ? obj.materialId : ''),
            from = obj.from ? obj.from : '',
            string = obj.data ? obj.data : ''
        let array = []
        try {
            if (id.length > 0) {
                const machiningInData = wx.getStorageSync('machiningInData')
                array = machiningInData[id]
            } else {
                array = api.jsonToArray(api.urlDecode(string))
            }
            this.setData({
                item: array,
                from: from
            })
        } catch (e) {
            wx.navigateBack({delta: 1})
            api.showToast('参数错误')
        }
    }
});